<template>
  <!-- 捐赠者卡片列表 -->
  <div class="donor-grid">
    <!-- 动态生成卡片 -->
    <div v-for="item in userList" :key="item.donorId" class="donor-card">
      <!-- 图片区域（可点击，懒加载） -->
      <a class="donor-image-link" @click="goToDetail(item)">
        <img
          class="donor-image__img"
          :data-src="item.photoUrl.split(',')[0] || deflutImage"
          alt="donor-photo"
          v-lazy
        />
      </a>

      <!-- 编号 & 资源数量 -->
      <div class="donor-meta">
        <!-- 左侧：编号 + 图标 -->
        <div class="donor-id">
          <span class="donor-id__text">{{ item.donorId }}</span>
          <!-- 收藏icon -->
          <img
            v-if="isFavorited(item)"
            v-lazy
            class="badge-icon"
            data-src="/img/5hhxAppTchkA.png"
            alt="frozen donation badge"
            @click="cancleClick(item, index)"
          />
          <img
            v-else
            v-lazy
            class="badge-icon"
            data-src="/img/ps9dtwpgbaua7m66ivh0f27hwfa63eyj6iiff8c5823.png"
            alt="badge icon"
            @click="saveClick(item, index)"
          />
        </div>

        <!-- 右侧：照片 & 视频数量 -->
        <div class="resource-count">
          <span class="count-text">{{ item.photoNum }}</span>
          <img
            class="count-icon"
            src="/img/psqzcr9q0kjugojilzr7idrcmlydf7dxjfb85477e7.png"
            alt="photo-icon"
          />
          <span class="count-text">{{ item.videoNum }}</span>
          <img
            class="count-icon"
            src="/img/psdbnghkpwnbg38ld11t5wbyq2tnajwarun1c00ad19.png"
            alt="video-icon"
          />
        </div>
      </div>

      <!-- 分隔线 -->
      <div class="divider"></div>

      <!-- 目前状态 -->
      <div
        class="donor-status"
        :class="{ 'donor-status--active': item.status }"
      >
        目前状态：{{ item.status }}
      </div>

      <!-- 详细信息表格 -->
      <div class="donor-info">
        <!-- 年龄 -->
        <div class="info-row">
          <span class="info-label">年龄</span>
          <span class="info-value">{{ item.ageAtDonation }}</span>
        </div>

        <!-- 身高 -->
        <div class="info-row">
          <span class="info-label">身高</span>
          <span class="info-value">{{ Math.floor(item.height) }}cm</span>
        </div>

        <!-- 体重 -->
        <div class="info-row">
          <span class="info-label">体重</span>
          <span class="info-value">{{ Math.floor(item.weight) }}kg</span>
        </div>

        <!-- 血型 -->
        <div class="info-row">
          <span class="info-label">血型</span>
          <span class="info-value">{{ item.bloodType }}</span>
        </div>

        <!-- 眼睛颜色 -->
        <div class="info-row">
          <span class="info-label">眼睛颜色</span>
          <span class="info-value">{{ item.eyeColor }}</span>
        </div>

        <!-- 头发颜色 -->
        <div class="info-row">
          <span class="info-label">头发颜色</span>
          <span class="info-value">{{ item.hairColor }}</span>
        </div>

        <!-- 最高学历 -->
        <div class="info-row">
          <span class="info-label">最高学历</span>
          <span class="info-value">{{ item.educationLevel }}</span>
        </div>

        <!-- 种族 -->
        <div class="info-row">
          <span class="info-label">种族</span>
          <span class="info-value">{{ item.ethnicity }}</span>
        </div>

        <!-- 捐献方式 -->
        <div class="info-row">
          <span class="info-label">开放身份捐献还是匿名？</span>
          <span class="info-value">{{
            item.anonymous ? "匿名" : "开放身份"
          }}</span>
        </div>
      </div>
    </div>
  </div>

  <!-- 分页组件 -->
  <div class="pagination-wrapper">
    <el-pagination
      :current-page="pageNum"
      :page-size="pageSize"
      :total="total"
      :page-sizes="[9, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup>
/* 1 原引入 */
import { onMounted, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useUserStore } from "@/store/modules/user";
import { deleteFavorites, insertFavorites } from "@/api/business/parents-to-be";
import { ElMessage } from "element-plus";

/* 2 props & emits */
const emits = defineEmits(["handleSizeChange", "handleCurrentChange"]);
const props = defineProps({
  userList: Array,
  total: Number,
  pageNum: Number,
  pageSize: Number,
});

/* 3 路由 */
const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

const rouPageNum = ref(1);
const rouPageSize = ref(9);
/* 4 懒加载指令 */
const vLazy = {
  mounted(el) {
    const io = new IntersectionObserver(
      (entries) =>
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            const img = entry.target;
            img.src = img.dataset.src || "";
            io.unobserve(img);
          }
        }),
      { threshold: 0.1 }
    );
    io.observe(el);
  },
};

/* 5 生命周期：地址栏有 query 就回写 */
onMounted(() => {
  const qn = route.query.pageNum;
  const qs = route.query.pageSize;
  if (qn) emits("handleCurrentChange", parseInt(qn));
  if (qs) emits("handleSizeChange", parseInt(qs));
});

/* 6 同步地址栏 */
const syncQuery = () => {
  router.replace({
    name: route.name,
    query: {
      ...route.query,
      pageNum: rouPageNum.value,
      pageSize: rouPageSize.value,
    },
  });
};

/* 7 原方法全部保留 */
const goToDetail = (item) =>
  router.push({
    path: "/parents/sperm-detail",
    query: {
      id: item.donorId,
      userId: item.userId,
      pageNum: props.pageNum,
      pageSize: props.pageSize,
    },
  });

const handleSizeChange = (val) => {
  rouPageSize.value = val;
  emits("handleSizeChange", val);
  syncQuery();
};
const handleCurrentChange = (val) => {
  rouPageNum.value = val;
  emits("handleCurrentChange", val);
  syncQuery();
};

const isFavorited = (item) =>
  item.favorites
    ? item.favorites.split(",").includes(String(userStore.id))
    : false;

const saveFlag = ref(false);
const saveClick = (item) => {
  if (saveFlag.value) return ElMessage.error("请不要连续点击");
  saveFlag.value = true;
  insertFavorites({
    userId: userStore.id,
    donorId: item.donorId,
    type: "sperm",
  }).then(() => {
    ElMessage.success("收藏成功");
    saveFlag.value = false;
    const favSet = new Set(item.favorites ? item.favorites.split(",") : []);
    favSet.add(String(userStore.id));
    item.favorites = Array.from(favSet).join(",");
  });
};

const cancleClick = (item) => {
  if (saveFlag.value) return ElMessage.error("请不要连续点击");
  saveFlag.value = true;
  deleteFavorites({
    userId: userStore.id,
    donorId: item.donorId,
    type: "sperm",
  }).then(() => {
    ElMessage.success("取消成功");
    saveFlag.value = false;
    const favSet = new Set(item.favorites ? item.favorites.split(",") : []);
    favSet.delete(String(userStore.id));
    item.favorites = Array.from(favSet).join(",");
  });
};
</script>

<style scoped lang="scss">
/* 默认字体与颜色 */
$font-default: "Microsoft YaHei", "微软雅黑", sans-serif;
$color-default: #333;

/* ========== 变量定义 ========== */
$border-color: #a2c4e8;
$text-primary: #2b5cab;
$text-secondary: #4d4d4d;
$divider-color: #e6e6e6;
$card-radius: 0.5rem;
$card-padding: 1.25rem;
$gap: 1.25rem;

/* ========== 布局 ========== */
/* 网格容器 */
.donor-grid {
  margin-top: 30px;
  display: grid;
  grid-template-columns: 1fr;
  gap: $gap;
  font-family: $font-default;
  color: $color-default;

  @media (min-width: 768px) {
    grid-template-columns: repeat(2, 1fr);
  }

  @media (min-width: 1024px) {
    grid-template-columns: repeat(3, 1fr);
  }
}

/* 单张卡片 */
.donor-card {
  border: 1px solid $border-color;
  border-radius: $card-radius;
  padding: $card-padding;
  font-family: $font-default;
  color: $color-default;
}

/* ========== 图片区域 ========== */
.donor-image-link {
  // display: block;
  cursor: pointer;
}

/* 原文件 scoped 里改这一处即可 */
/* ===== 图片区域 ===== */
.donor-image-link {
  display: block;
  width: 100%; /* 让父级有宽度，aspect-ratio 才能生效 */
  height: auto !important;
}

/* 深度选中：绕过 scoped 哈希 & 权重问题 */
:deep(.donor-image__img) {
  aspect-ratio: 3 / 4 !important; /* 锁死 321:459 */
  object-fit: cover !important; /* 不想裁就改成 contain */
  width: 100%;
}

/* ========== 编号 & 资源数量 ========== */
.donor-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24px 0;
  font-family: $font-default;
  color: $color-default;
}

.donor-id {
  display: flex;
  align-items: center;
  gap: 15px;

  &__text {
    font-size: 24px;
    color: $text-secondary;
    font-family: $font-default;
  }
}

.resource-count {
  display: flex;
  align-items: center;
  gap: 15px;

  .count-text {
    font-size: 16px;
    color: $text-secondary;
    font-family: $font-default;
  }

  .count-icon {
    width: 22px;
    height: 16px;
  }
}

.icon {
  width: 24px;
  height: 24px;
}

/* ========== 分隔线 ========== */
.divider {
  height: 1px;
  background-color: $divider-color;
}

/* ========== 状态 ========== */
.donor-status {
  margin-top: 20px;
  text-align: center;
  font-size: 16px;
  color: $text-secondary;
  font-family: $font-default;

  &--active {
    color: $text-primary;
  }
}

/* ========== 详细信息 ========== */
.donor-info {
  margin-top: 38px;
  font-family: $font-default;
  color: $color-default;
}

.info-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  padding: 8px 0;
  border-bottom: 1px solid #e0e0e0;

  &:last-child {
    border-bottom: none;
  }

  .info-label {
    font-size: 16px;
    color: $text-secondary;
    line-height: 24px;
    font-family: $font-default;
  }

  .info-value {
    font-size: 16px;
    color: $text-primary;
    line-height: 24px;
    text-align: right;
    font-family: $font-default;
  }
}

/* ========== 分页 ========== */
.pagination-wrapper {
  padding: 40px 0;
  display: flex;
  justify-content: center;
  font-family: "Microsoft YaHei", "微软雅黑", sans-serif;
  color: #333;
}
</style>
